package cn.cas.mango.service;

import cn.cas.mango.dto.HotListDetail;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
@Slf4j
public class ModelService {

  @Autowired
  private ConfigService configService;
  private JSONArray wrapJsonArray(List<HotListDetail> hotListDetails) {
    JSONArray jsonArray = new JSONArray();
    for (HotListDetail hotListDetail : hotListDetails) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("title", hotListDetail.getTitle() == null ? "" : hotListDetail.getTitle());
      jsonObject.put("content", hotListDetail.getDesc() == null ? "" : hotListDetail.getDesc());
      jsonObject.put("time", hotListDetail.getInsert_time());
      jsonArray.add(jsonObject);
    }
    return jsonArray;
  }
  public JSONObject getModelSummary(List<HotListDetail> hotListDetails) {
    String url = configService.getModelSummaryUrl();
    JSONArray jsonArray = wrapJsonArray(hotListDetails);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("data", jsonArray);
    String jsonObjectString = jsonObject.toString();
    StringBuilder response = new StringBuilder();
    try {
      URL urlObj = new URL(url);
      HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
      con.setRequestMethod("POST");
      con.setRequestProperty("Content-Type", "application/json; utf-8");
      con.setRequestProperty("Accept", "application/json");
      con.setDoOutput(true);

      try (OutputStream os = con.getOutputStream()) {
        byte[] input = jsonObjectString.getBytes(StandardCharsets.UTF_8);
        os.write(input, 0, input.length);
      }
      try (BufferedReader br = new BufferedReader(
          new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
        String responseLine;
        while ((responseLine = br.readLine()) != null) {
          response.append(responseLine.trim());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }return JSONObject.parseObject(response.toString());
  }
}
